import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:multi_shop/utils/index.dart';
import 'package:pinput/pinput.dart';

enum PinType { login, payment }

class SetPinPage extends StatefulWidget {
  const SetPinPage({super.key});

  @override
  State<SetPinPage> createState() => _SetPinPageState();
}

class _SetPinPageState extends State<SetPinPage> {
  static const _len = 6;
  late final PinType type; // 从 Get.arguments 读取

  final _newCtrl = TextEditingController();
  final _confirmCtrl = TextEditingController();
  final _newNode = FocusNode();
  final _confirmNode = FocusNode();

  String _newError = '';
  String _confirmError = '';

  bool get _ready =>
      _newCtrl.text.length == _len && _confirmCtrl.text.length == _len;

  @override
  void initState() {
    super.initState();
    type = (Get.arguments as PinType?) ?? PinType.login;
    _newCtrl.addListener(_onChanged);
    _confirmCtrl.addListener(_onChanged);
  }

  @override
  void dispose() {
    _newCtrl.removeListener(_onChanged);
    _confirmCtrl.removeListener(_onChanged);
    _newCtrl.dispose();
    _confirmCtrl.dispose();
    _newNode.dispose();
    _confirmNode.dispose();
    super.dispose();
  }

  void _onChanged() {
    setState(() {}); // 刷新按钮可点击状态
  }

  String get _title => type == PinType.login ? '设置登录密码' : '设置支付密码';

  bool _isWeak(String pin) {
    const commons = {'000000', '111111', '123456', '654321', '999999'};
    if (commons.contains(pin)) return true;
    if (pin.split('').toSet().length == 1) return true; // 全相同
    return false;
  }

  void _clearErrors() {
    _newError = '';
    _confirmError = '';
  }

  void _resetAll() {
    _newCtrl.clear();
    _confirmCtrl.clear();
    _clearErrors();
    _newNode.requestFocus();
    setState(() {});
  }

  void _onCompletePressed() {
    _clearErrors();
    final a = _newCtrl.text;
    final b = _confirmCtrl.text;

    if (a.length != _len) {
      setState(() => _newError = '请输入$_len位数字');
      _newNode.requestFocus();
      return;
    }
    // if (_isWeak(a)) {
    //   setState(() => _newError = '密码过于简单，避免连续/重复数字');
    //   _newNode.requestFocus();
    //   return;
    // }
    if (b.length != _len) {
      setState(() => _confirmError = '请再次输入$_len位数字确认');
      _confirmNode.requestFocus();
      return;
    }
    if (a != b) {
      setState(() => _confirmError = '两次输入不一致');
      _confirmCtrl.clear();
      _confirmNode.requestFocus();
      return;
    }
    debugPrint('a: $a, b: $b');
    toastCenter('已完成');

    Get.back(result: a);
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    PinTheme baseTheme(Color border) => PinTheme(
      width: 52,
      height: 60,
      textStyle: theme.textTheme.headlineSmall,
      decoration: BoxDecoration(
        color: theme.colorScheme.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: border),
      ),
    );

    final defaultTheme = baseTheme(theme.colorScheme.outline.withOpacity(.4));
    final focusedTheme = baseTheme(theme.colorScheme.primary).copyWith(
      decoration: BoxDecoration(
        color: theme.colorScheme.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: theme.colorScheme.primary, width: 2),
      ),
    );

    return Scaffold(
      appBar: AppBar(title: Text(_title), centerTitle: true),
      body: SafeArea(
        minimum: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '请输入并确认 $_len 位数字密码',
              style: theme.textTheme.bodyLarge?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 16),

            // 新密码
            Text('新密码', style: theme.textTheme.labelLarge),
            const SizedBox(height: 8),
            Center(
              child: Pinput(
                controller: _newCtrl,
                focusNode: _newNode,
                length: _len,
                obscureText: true,
                obscuringCharacter: '•',
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                defaultPinTheme: defaultTheme,
                focusedPinTheme: focusedTheme,
              ),
            ),
            if (_newError.isNotEmpty) ...[
              const SizedBox(height: 6),
              Text(
                _newError,
                textAlign: TextAlign.center,
                style: TextStyle(color: theme.colorScheme.error),
              ),
            ],

            const SizedBox(height: 18),

            // 确认密码
            Text('确认密码', style: theme.textTheme.labelLarge),
            const SizedBox(height: 8),
            Center(
              child: Pinput(
                controller: _confirmCtrl,
                focusNode: _confirmNode,
                length: _len,
                obscureText: true,
                obscuringCharacter: '•',
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                defaultPinTheme: defaultTheme,
                focusedPinTheme: focusedTheme,
              ),
            ),
            if (_confirmError.isNotEmpty) ...[
              const SizedBox(height: 6),
              Text(
                _confirmError,
                textAlign: TextAlign.center,
                style: TextStyle(color: theme.colorScheme.error),
              ),
            ],

            const Spacer(),

            // 底部按钮
            FilledButton(
              onPressed: _ready ? _onCompletePressed : null,
              style: FilledButton.styleFrom(
                minimumSize: const Size.fromHeight(48),
              ),
              child: const Text('完成设置'),
            ),
            const SizedBox(height: 10),
            OutlinedButton(
              onPressed: _resetAll,
              style: OutlinedButton.styleFrom(
                minimumSize: const Size.fromHeight(48),
              ),
              child: const Text('清空重填'),
            ),
          ],
        ),
      ),
    );
  }
}
